/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.client.Util;



import net.bioteam.appweb.gwt.apps.client.ReloginWindow;
import net.bioteam.appweb.gwt.apps.client.StaticHolder;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.StatusCodeException;
import com.smartgwt.client.util.SC;


public abstract class ApplicationCallBack<T> implements AsyncCallback<T>, Command
{
	
	public void onFailure(Throwable caught)
	{
		if (onFailureBefore(caught))
		{
			if (caught instanceof StatusCodeException)
			{
				StatusCodeException se = (StatusCodeException) caught;
				if (se.getStatusCode() == 499)
				{
					ReloginWindow rwin=StaticHolder.getReloginWindow();
					rwin.addCommand(this);
					
					
					
					//StaticHolder.loginPanel.removeSession();
					if (!rwin.isVisible())
					{
						rwin.messageLabel.setContents("   ");
						rwin.show();
					}
					//SC.warn(se.getMessage(), StaticHolder.dumpB);
					//LoginDialog.getLoginDialog(caught.getMessage(), this);
				} else if (se.getStatusCode() == 401)
				{
					SC.warn(se.getMessage(), StaticHolder.dumpB);
					//LoginDialog.getLoginDialog(caught.getMessage(), this);
				} else if (se.getStatusCode() == 403)
				{
					SC.warn(se.getMessage(), StaticHolder.dumpB);
				} else
				{
					onFailureAfter(caught);
				}
			} else
			{
				onFailureAfter(caught);
			}
		}

	}

	/**
	 * 
	 * @param caught
	 *            the exeception from client.
	 * @return whether the exception is handled completely.
	 */
	protected boolean onFailureBefore(Throwable caught)
	{
		return true;
	}

	protected void onFailureAfter(Throwable caught)
	{
		// default implementation.
		SC.warn(caught.getMessage(), StaticHolder.dumpB);
	}

	public void onSuccess(T result)
	{
		/*
		 * extra task here. There are nothing right now
		 */

		// specific task to handle the call from the RPC end.
		onSuccessAfter(result);
	}

	/**
	 * implement by subclass for the application-specific task
	 * 
	 * @param result
	 */
	protected void onSuccessAfter(T result)
	{
	}

	// execute command should be implemented by subclass to
	// perform the async RPC call.
	//this should be the AsyncCallback instance to handle the remote response.
}
